/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <aki/jsbind.h>
#include <unistd.h>
#include "hilog/log.h"

class Message {
public:
    std::string message;
    int length;
    Message() = default;
    explicit Message(std::string info)
    {
        message = info + " init";
        length = message.size();
    }
};

JSBIND_CLASS(Message)
{
    JSBIND_CONSTRUCTOR<>();
    JSBIND_CONSTRUCTOR<std::string>();
    JSBIND_PROPERTY(message);
    JSBIND_PROPERTY(length);
}

static std::string CallJsFunc(std::string name)
{
    std::string res = "";
    if (auto func = aki::JSBind::GetJSFunction(name)) {
        res = func->Invoke<std::string>();
    } else {
        AKI_LOG(ERROR) << "GetJSFunction " << name << " failed!";
    }
    return res;
}

static Message AsyncTaskMessageReturnMessage(Message &info, std::string message)
{
    info.message = message + " reply";
    info.length = info.message.size();
    return info;
}

JSBIND_GLOBAL()
{
    JSBIND_PFUNCTION(AsyncTaskMessageReturnMessage);
    JSBIND_FUNCTION(CallJsFunc);
}

class NapiTest {
public:
    std::string requestMsg;
    std::string responseMsg;
    aki::ArrayBuffer buffer;
    NapiTest()
    {
        requestMsg = "set the request";
        responseMsg = "set the response";
    }
    void SetMsg(std::string msg)
    {
        if (msg.length() > 0) {
            OH_LOG_INFO(LOG_APP, "set message : %{public}s", msg.c_str());
            requestMsg = msg;
        }
    }
    
    void  StartGetData(int num, std::string msg, std::function<std::string (int args, std::string msg)> func)
    {
        std::string val = func(num, msg);
        OH_LOG_INFO(LOG_APP, "tGetData : %{public}s", val.c_str());
    }
    
    std::string GetMsg()
    {
        return responseMsg;
    }
};

JSBIND_CLASS(NapiTest) {
    JSBIND_CONSTRUCTOR<>();
    JSBIND_PROPERTY(requestMsg);
    JSBIND_PROPERTY(responseMsg);
    JSBIND_PROPERTY(buffer);
    JSBIND_METHOD(SetMsg);
    JSBIND_METHOD(GetMsg);
    JSBIND_PMETHOD(StartGetData);
}

JSBIND_ADDON(worker);